package com.bantang.bizmq;


import com.bantang.common.ResultUtils;
import com.bantang.manager.AiManager;
import com.bantang.model.entity.Chart;
import com.bantang.service.ChartService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.bantang.bizmq.BiMqConstant.BI_QUEUE_NAME;


@Component
@Slf4j
public class BiMessageConsumer {

    @Resource
    ChartService chartService;

    @Resource
    AiManager aiManager;

    @SneakyThrows
    @RabbitListener(queues = {BI_QUEUE_NAME},ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag){

        if (StringUtils.isBlank(message)){
            channel.basicNack(deliveryTag,false,false);
            handleCharUpdateError(null,"系统错误请重试");
        }
        Chart chart = chartService.getById(Long.valueOf(message));

        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String charData = chart.getChartData();


        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setChartData("chart_"+chart.getUserId()+"_"+chart.getId());
        updateChart.setStatus("running");

        boolean b = chartService.updateById(updateChart);

        if (!b){
            channel.basicNack(deliveryTag,false,false);
            handleCharUpdateError(chart.getId(),"更改图表执行中状态失败");
        }

        StringBuilder messageBuilder = new StringBuilder();

        if (StringUtils.isNotBlank(chartType)){
            goal += "请使用"+chartType;
        }

        messageBuilder.append("分析需求：").append("\n");
        messageBuilder.append(goal).append("\n");
        //读取Excel文件 进行处理
        messageBuilder.append("原始数据："+charData).append("\n");

        //调用AI接口分析数据
        String verdictMessage = aiManager.doChat(messageBuilder.toString());

        String verdictMessages[] = verdictMessage.split("【【【【【|】】】】】");

        if (verdictMessages.length < 3){
            channel.basicNack(deliveryTag,false,false);
            ResultUtils.error(999,"AI生成错误");
        }

        String genChart = verdictMessages[1].trim();
        String genResult = verdictMessages[2].trim();

        Chart updateChartResult = new Chart();
        updateChartResult.setId(chart.getId());
        updateChartResult.setStatus("succeed");
        updateChartResult.setGenChart(genChart);
        updateChartResult.setGenResult(genResult);

        boolean updateResult = chartService.updateById(updateChartResult);

        if (!updateResult){
            channel.basicNack(deliveryTag,false,false);
            handleCharUpdateError(chart.getId(),"图表成功状态更新失败");
        }

        channel.basicAck(deliveryTag,false);
    }

    private void handleCharUpdateError(Long chartId,String errorMessage){

        if (chartId == null){
            log.error("更新图表状态失败"+errorMessage);
        }
        Chart errorChart = new Chart();
        errorChart.setId(chartId);
        errorChart.setStatus("failed");
        errorChart.setExecMessage(errorMessage);

        boolean b = chartService.updateById(errorChart);
        if (!b){
            log.error("更新图表状态失败"+chartId+","+errorMessage);
        }
    }
}
